﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using System.Xml;

namespace Interface_ManTuLuoBA.Tools
{
    public static class MyTools
    {
        /// <summary>
        /// xml序列化方法（采用了JSON作为中间类型转换）
        /// </summary>
        /// <typeparam name="T">接受类型</typeparam>
        /// <param name="node">xml单元数据</param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(XmlNode node)
        {
            string JSON = JsonConvert.SerializeXmlNode(node);
            JSON = JSON.Substring(JSON.IndexOf(":") + 1);
            JSON = JSON.Substring(0, JSON.Length - 1);
            return JsonConvert.DeserializeObject<T>(JSON);
        }

        /// <summary>
        /// XmlDocument转换为字符串的工具类
        /// </summary>
        /// <param name="xmlDoc">XmlDocument对象</param>
        /// <returns>字符串</returns>
        public static string ConvertXmlToString(XmlDocument xmlDoc)
        {
            MemoryStream mStream = new MemoryStream();
            XmlTextWriter xmlWriter = new XmlTextWriter(mStream, null);
            xmlWriter.Formatting = System.Xml.Formatting.Indented;
            xmlDoc.Save(xmlWriter);
            StreamReader sr = new StreamReader(mStream, System.Text.Encoding.UTF8);
            mStream.Position = 0;
            string XmlStr = sr.ReadToEnd();
            sr.Close();
            mStream.Close();
            return XmlStr;
        }

        /// <summary>
        /// 根据路径返回文件中的字符串
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static String ReadPathStr(string path)
        {
            String res = "";
            StreamReader sRead = new StreamReader(path, Encoding.Default);
            String line;
            while ((line = sRead.ReadLine()) != null)
            {
                res += line;
            }
            return res;
        }
    }
}